package com.cly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.domain.SysUser;
import com.cly.domain.SysUserRole;
import com.cly.mapper.SysUserMapper;
import com.cly.mapper.SysUserRoleMapper;
import com.cly.service.SysUserRoleService;
import com.cly.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 分页查询后台管理员的接口
     * 分页查询不需要缓存
     *
     * @param page
     * @param sysUser
     * @return
     */
    @Override
    public Page<SysUser> findSysUserByPage(Page<SysUser> page, SysUser sysUser) {
        //分页查询根据时间排序
        page.addOrder(OrderItem.desc("create_time"));
        return sysUserMapper.selectPage(page,new LambdaQueryWrapper<SysUser>()
                .like(StringUtils.hasText(sysUser.getUsername()),SysUser::getUsername, sysUser.getUsername())
        );
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(SysUser sysUser) {
        log.info("新增管理员，操作人id:{}",sysUser.getCreateUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        //处理密码 加密 存密文
        String password = sysUser.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePass = passwordEncoder.encode(password);
        sysUser.setPassword(encodePass);
        int inset = sysUserMapper.insert(sysUser);
        if (inset > 0){
            //操作角色用户表
            Long userId = sysUser.getUserId();
            List<Long> roleIdList = sysUser.getRoleIdList();
            //循环创建对象 插入数据 不要再循环中操作数据库
            ArrayList<SysUserRole> sysUserRoles = new ArrayList<>(roleIdList.size() * 2);
            roleIdList.forEach(roleId ->{
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                sysUserRoles.add(sysUserRole);
            });
            //操作数据库的时候 提交事物 连接的操作耗性能 指定每次提交的数量可以提升mysql的吞吐量
            sysUserRoleService.saveBatch(sysUserRoles);
        }
        return inset > 0;
    }
}
